#!/usr/bin/perl
# ----------------------------------------------------------------------------
#
#  (c) Copyright 2006 TradeExtender
# 
#  This software is proprietary to  embodies the confidential technology 
#  of TradeExtender. Possession, use, duplication or dissemination of the 
#  software and media is authorized only pursuant to a valid written license 
#  from TradeExtender.
#

use strict;
use lib "/var/www/vhosts/kantelpunten.com/httpdocs/pl/lib";
use lib "lib";
BEGIN {
    delete $INC{"Kantelpunten/Helper.pm"};
    delete $INC{"Kantelpunten/Process.pm"};
    delete $INC{"Kantelpunten/MyContent.pm"};
#    delete $INC{"Kantelpunten/MyRobots.pm"};
}
use Kantelpunten::Helper;
use Kantelpunten::Process;
use Kantelpunten::MyContent;
use Kantelpunten::MyRobots;
use POSIX qw(strftime);
use Data::Dumper;


local our $stocks;
local our $data;
local our $param;
local our $type;
local our $tipsite;

show_free_content();
exit(0);

sub show_free_content()
{
	my $q = CGI->new;

	$param->{type}	      = $q->param('type');
	$param->{content}	  = $q->param('content');
	$param->{country}     = $q->param('country');
	$param->{font}	      = $q->param('font');
	$param->{bg_color}    = $q->param('bg_color');
	$param->{text_color}  = $q->param('text_color');
	$param->{mbg_color}   = $q->param('mbg_color');
	$param->{mtext_color} = $q->param('mtext_color');
	$param->{link_color}  = $q->param('link_color');
	$param->{vlink_color} = $q->param('vlink_color');
	$param->{alink_color} = $q->param('alink_color');
	$param->{id}          = $q->param('id');
	
	$param->{type}        = "button"  unless defined($param->{type});
	$param->{content}     = "beide"   unless defined($param->{content});
	$param->{country}     = "alle"    unless defined($param->{country});
	$param->{font}        = "trebuchet ms" unless defined($param->{font});
	$param->{td_height}   = 10;
	$param->{bg_color}    = "C8E1FA" unless defined($param->{bg_color});
	$param->{text_color}  = "0000CC" unless defined($param->{text_color});
	$param->{mbg_color}   = "00FF00" unless defined($param->{mbg_color});
	$param->{mtext_color} = "000000" unless defined($param->{mtext_color});
	$param->{link_color}  = $param->{text_color} unless defined($param->{link_color});
	$param->{vlink_color} = "000099" unless defined($param->{vlink_color});
	$param->{alink_color} = $param->{vlink_color} unless defined($param->{alink_color});
	$param->{perc}        = 1; 		# lowest allowed percedntage current semi harcoded
	
	# herewe have some preconfigured setting so that it easy to change
	if (defined($param->{id}))
	{
		if ($param->{id} eq "bk")
		{
			$param->{content} 	  = "kantel";
			$param->{country}     = "alle";
			$param->{font}        = "trebuchet ms";
			$param->{bg_color}    = "FFFFFF";
			$param->{text_color}  = "000000";
			$param->{mbg_color}   = "FFFFFF";
			$param->{mtext_color} = "000000";
			$param->{link_color}  = "000000";
			$param->{vlink_color} = "808080";
			$param->{alink_color} = "808080";
		}
	}
	
	# some extra sanity checkse
	$param->{content} = "beide" if (($param->{content} ne "beide") && ($param->{content} ne "kantel") && ($param->{content} ne "winst"));
	$param->{country} = "alle"  if (($param->{country} ne "alle")  && ($param->{country} ne "nl")     && ($param->{country} ne "be"));
	my $remote_ip = init_helper();
	set_robot(get_robot());
	init_process();
	init_content();
	
	$param->{referer} = translate_referer($ENV{'HTTP_REFERER'});
	
	my @errors;
	
	$type = translate_content_type($param->{type});
	if (!defined($type))
	{
		push (@errors, "Onbekend type");
		log_problem("Verkeerde content format $param->{type}");
	}
	my $mkt;
	$mkt = get_nl_mask if ($param->{country} eq "nl");
	$mkt = get_be_mask if ($param->{country} eq "be");
	$stocks = get_stocks_market($mkt);
	if (!defined($stocks))
	{
		push (@errors, "Geen aandelen");
		log_problem("GKC: Probleem met het lezen van de aandelen data.");
	}

	$data = read_all_quote_data();
	if (!defined($data))
	{
		push (@errors, "Geen data");
    	log_problem("GKC: Probleem met het lezen van de kantelpunten data.");
	}

	if ((@errors > 0) || !defined($type->{page}))
	{
		write_referer_access_data($param->{referer}, 0, 0, $remote_ip);
		print_mini_error_doc(@errors);
	    exit(0);
	}

	my $tp = get_tip_site($param->{referer});
	if (defined($tp) && defined($tp->{"0000"}))
	{
		$tipsite = $tp->{"0000"};
		$param->{tipsite} = $tipsite->{id};
	}
	
	write_referer_access_data($param->{referer}, $type->{itype}, $param->{tipsite}, $remote_ip);
	if ($param->{referer} > 1)
	{
		write_access_data($remote_ip, $type->{page});
	}

	make_free_content_html();
}
	    
sub make_free_content_html(@)
{
	print_header("+1s");
    print_pre_doc();
    my $mini = css_mini_pies();
    print <<EndOfText;
<head>
 <meta http-equiv="Content-Language" content="nl">
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <meta http-equiv="Cache-Control" content="NO-CACHE">
 <meta http-equiv="Pragma" content="NO-CACHE">
 <meta name="Author" content="Floppy & Toppy Kantelpunten">
 <meta name="Copyright" content="&copy; 2006-2008 TradeExtender">
 <meta name="Description" content="Deze gratis content wordt u aangeboden door Kantelpunten de Beursscanner. Weinig tijd en toch aktief beurzen dan is dit iets voor u !">
 <meta name="Keywords" content="kantelpunten, beursscanner, adviezen, aandelen, beleggen, gratis">
 <meta name="Robots" content="INDEX,FOLOW">
 <meta name="Googlebot" content="ARCHIVE">
 <title>Dagelijkse gratis kantelpunten adviezen op www.kantelpunten.com</title>
 <base target="_blank">
 <style>a{text-decoration: none}</style>
 <style fprolloverstyle="">A:hover {color: $param->{link_color}; text-decoration: underline; font-family: $param->{font}; font-size: 10pt}</style>
 <style type="text/css">
$mini
  a.up {
   display: block;
   background: url(http://www.kantelpunten.com/pics/icon/ICOONhigh.gif) no-repeat;
   vertical-align: middle;
   border: 0px solid;
   float: none;
   margin-left: auto;
   margin-right: auto;
   margin-top: 0px;
   overflow: hidden;
   width: 11px; 
   height: 11px; }
  a.do {
   display: block;
   background: url(http://www.kantelpunten.com/pics/icon/ICOONlow.gif) no-repeat;
   vertical-align: middle;
   border: 0px solid;
   float: none;
   margin-left: auto;
   margin-right: auto;
   margin-top: 0px;
   overflow: hidden;
   width: 11px; 
   height: 11px; }
  table {
	border-width: 0;
	border-spacing: 0;
	border-padding: 0;
	background-color: $param->{bg_color}; }   
  tr { font-family: trebuchet ms; }
  td {
	border-width: 0;
	border-style: 0;
	padding: 0;
	spacing: 0;
    color: $param->{text_color};
    font-size: 10pt;
    height: $param->{td_height};
    overflow: hidden;
    text-align: center; }
  td.max { 
	color: $param->{mtext_color};
	background-color: $param->{mbg_color}; }
 </style> 
 <body style="background-color: $param->{bg_color}; color: $param->{text_color};"
       topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0"
       scroll="no" alink="$param->{alink_color}" link="$param->{link_color}" vlink="$param->{vlink_color}">
EndOfText
    make_free_content();
    print "</body>\n";
    print_post_doc();
}

sub print_mini_error_doc(@)
{
	print_header("+1s");
    print_pre_doc();
    print <<EndOfText;
<head>
 <meta http-equiv="Content-Language" content="nl">
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <meta http-equiv="Cache-Control" content="NO-CACHE">
 <meta http-equiv="Pragma" content="NO-CACHE">
 <meta name="Author" content="Floppy & Toppy Kantelpunten">
 <meta name="Copyright" content="&copy; 2006-2008 TradeExtender">
 <meta name="Description" content="Deze gratis content wordt u aangeboden door Kantelpunten de Beursscanner. Weinig tijd en toch aktief beurzen dan is dit iets voor u !">
 <meta name="Keywords" content="kantelpunten, beursscanner, adviezen, aandelen, beleggen, gratis">
 <meta name="Robots" content="INDEX,FOLOW">
 <meta name="Googlebot" content="ARCHIVE">
 <title>Dagelijkse gratis kantelpunten adviezen op www.kantelpunten.com</title>
 <base target="_blank">
 <style>a{text-decoration: none}</style>
 <style fprolloverstyle="">A:hover {color: $param->{link_color}; text-decoration: underline; font-family: $param->{font}; font-size: 10pt}</style>
 <style type="text/css">
  table {
	border-width: 0;
	border-spacing: 0;
	border-padding: 0;
	background-color: $param->{bg_color}; }   
  tr { font-family: trebuchet ms; }
  td {
	border-width: 0;
	border-style: 0;
	padding: 0;
	spacing: 0;
    color: $param->{text_color};
    font-size: 10pt;
    height: $param->{td_height};
    overflow: hidden;
    text-align: center; }
 </style> 
 <body style="background-color: $param->{bg_color}; color: $param->{text_color};"
       topmargin="0" bottommargin="0" leftmargin="0" rightmargin="0"
       scroll="no" alink="$param->{alink_color}" link="$param->{link_color}" vlink="$param->{vlink_color}">
 <div style="align:left; overflow:hidden;">
 <table border="0" cellpadding="0" cellspacing="0">
 <tbody>
 <tr><td>Fouten opgetreden:</td></tr>
EndOfText
	for (my $i = 0; $i < @_; $i++)
	{
		print " <tr><td>" . @_[$i] . "</td></tr>\n";
	}
	print <<EndOfText;
 <tr><td><a href="http://www.kantelpunten.com" title="Gratis content geleverd door www.kantelpunten.com">&copy;&nbsp;kantelpunten.com</a></td></tr>
 </tbody>
 </table>
</body>
EndOfText
    print_post_doc();
}


sub get_scan_ids(@)
{
	my ($random) = @_;
	my @ids;
    my $cor;
    my $t;
    my $num;
    my $perc;
    # first make a list with the ids what to adde depends on the type
    foreach my $i (keys %$data)
    {
        next if ($i == 0);
        next if (!defined($stocks->{$i}));
  		next if (!is_new_kantelpunt($data->{$i}->{scan_time}));

        $num = $data->{$i}->{num_ok} + $data->{$i}->{num_nok};
    	$num = 1 if ($num == 0);
    	$perc = $data->{$i}->{num_ok} / $num * 100;
        $t = sprintf("%03d.%03d:%03d", int($perc), ($perc*1000)%1000, $i);
        $cor->{$t} = $i;
    }

    if (defined($random))
    {
    	my @stk = keys %$cor;
    	my $i;
	    while(@stk)
    	{ 
	    	$i = splice(@stk, rand(@stk), 1);
        	push @ids, $cor->{$i};
	    }
    }
    else
    {
	    my @sort = reverse sort keys %$cor;
   		foreach my $i (@sort)
   		{
       		push @ids, $cor->{$i};
    	}
	}
    return @ids;
}

sub get_success_ids(@)
{
	my ($random) = @_;
	my @ids;
    my $difs;
    my $num;
    my $t;
    # first make a list with the ids what to adde depends on the type
    foreach my $i (keys %$data)
    {
        next if ($i == 0);
        next if (!defined($stocks->{$i}));
        next if ($data->{$i}->{state} <= 1);	# never bought
        next if ($data->{$i}->{max_dif} < $param->{perc});

        $t = sprintf("%04d.%03d:%03d", int(abs($data->{$i}->{max_dif})), (abs($data->{$i}->{max_dif})*1000)%1000, $i);
        $difs->{$t} = $i;

        $num = int(($data->{$i}->{max_date}-$data->{$i}->{bought_on})/(24*3600));
		$num++;
    	$num = 0 if ($num < 0);
    	$data->{$i}->{max_days} = $num;
    }

    if (defined($random))
    {
    	my @stk = keys %$difs;
    	my $i;
	    while(@stk)
    	{ 
	    	$i = splice(@stk, rand(@stk), 1);
        	push @ids, $difs->{$i};
	    }
    }
    else
    {
	    my @sort = reverse sort keys %$difs;
    	foreach my $i (@sort)
   		{
       		push @ids, $difs->{$i};
   		}
	}
    return @ids;
}

sub get_koop_text(@)
{
	my ($id, $ref) = @_;

    my $title = "title=\"";
    $title .= ($data->{$id}->{scan_type} eq "+") ? "koop" : "verkoop";
    $title .= "-signaal, juistheid, trigger-koers en aandeel\"";

    my $img = make_mini_pie_img($stocks->{$id}->{stock}, $stocks->{$id}->{cur_idx}, $data->{$id}, undef, 47000+$id, $title);
   	$img = "&nbsp;" unless defined($img);

	my $text = "";
	my $class = ($data->{$id}->{scan_type} eq "+") ? "up" : "do";
	$text .= "<td><a class=\"$class\" href=\"${ref}${id}\" rel=\"nofollow\" $title></a></td>";
	$text .= "<td>$img</td>";
	$text .= "<td>" . sprintf("%.2f", $data->{$id}->{scan_trigger}) . "</td>";
	my $name = substr($stocks->{$id}->{index_name}, 0, $type->{len_stock});
	$name =~ s/ /&nbsp;/g;
	$text .= "<td><a href=\"${ref}${id}\" rel=\"nofollow\" $title>$name</a></td>";
	
	return $text;
}

sub get_success_text(@)
{
	my ($id, $ref) = @_;

    my $title = "title=\"#dagen, juistheid, winst sinds koop en aandeel\"";

    my $img = make_mini_pie_img($stocks->{$id}->{stock}, $stocks->{$id}->{cur_idx}, $data->{$id}, undef, 47000+$id, $title);
    $img = "&nbsp;" unless defined($img);

    my $text = "";
    $text .= "<td class=\"max\">" . (($data->{$id}->{max_days} != 0) ? $data->{$id}->{max_days} : "Z") . "</td>";
	$text .= "<td>$img</td>";
    $text .= "<td class=\"max\">" . (($data->{$id}->{max_dif} != 0.0) ? sprintf("%.2f%", abs($data->{$id}->{max_dif})) : "&nbsp;") . "</td>";
	my $name = substr($stocks->{$id}->{index_name}, 0, $type->{len_stock});
	$name =~ s/ /&nbsp;/g;
	$text .= "<td><a href=\"${ref}${id}\" rel=\"nofollow\" $title>$name</a></td>";

	return $text;
}
	
sub make_free_content()
{
	my ($market) = @_;
	
    my $ref 		= "http://www.kantelpunten.com/pl/Redirect.pl?page=";
    my $time 		= $data->{0}->{kantel_time};
    my $upd 		= strftime("%d-%m\n", localtime($time));
	my $copy_kantel = "<a href=\"http://www.kantelpunten.com\" title=\"Gratis content geleverd door www.kantelpunten.com\">&copy;&nbsp;kantelpunten.com</a>";
	my $advies 		= "<a href=\"${ref}9983\" title=\"Toon alle kantelpunten!\"><b><i>Adviezen van $upd</i></b></a>";
	my $tiptitle    = ((($type->{width}/$type->{col}) <= 125) && ($type->{col} < 4)) ? "tip" : "partner";
	my $tip	 		= "<a href=\"http://www.kantelpunten.com/pl/gratis-beurssite-adverteren.pl\" title=\"Gratis uw beurs-site hier? Kijk hier hoe!\" rel=\"nofollow\">$tiptitle</a>:&nbsp;";
	my $tip_site    = "";
	if (defined($tipsite))
	{
		$tip_site 	= "<a href=\"$tipsite->{main_url}\" title=\"$tipsite->{title}\">$tipsite->{disp_name}</a>";
	}

    my @koop = get_scan_ids("random");
    my @suc = get_success_ids("random");

    my $nkoop;
    my $nsuc;
    my $empty;
    
	print "<div style=\"align:left; width:$type->{width}; height:$type->{height}; overflow:hidden;\">\n";
    print "<table width=\"$type->{width}\" height=\"$type->{height}\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">\n";
    print "<tbody>\n";
    
    if ($type->{col} == 1)
    {
	    if ($param->{content} eq "kantel")
	    {
			$nkoop = $type->{num};
	    	$nsuc  = 0;
    		$empty = $nkoop - @koop if ($nkoop > @koop);
		}
		elsif ($param->{content} eq "winst")
		{
			$nkoop = 0;
			$nsuc  = $type->{num};
    		$empty = $nsuc - @suc if ($nsuc > @suc);
		}
		else
	    {
			$nkoop = int($type->{num} / 2);
	    	$nsuc  = $nkoop + ($type->{num} % 2);
    	  	$empty = 0;
    		$nsuc += $nkoop - @koop if ($nkoop > @koop);
    		$empty = $nsuc - @suc if ($nsuc > @suc);
		}

      	print "<tr><td colspan=\"4\">$advies</td></tr>\n";
	    for (my $i = 0; $i < $nkoop; $i++)
    	{
   	    	print "<tr>" . get_koop_text(@koop[$i], $ref) . "</tr>\n";
    	}
    	for (my $i = 0; $i < $nsuc; $i++)
    	{
   	    	print "<tr>" . get_success_text(@suc[$i], $ref) . "</tr>\n";
    	}
    	for (my $i = 0; $i < $empty; $i++)
    	{
	    	print "<tr><td colspan=\"4\">&nbsp;</td></tr>\n";
    	}
    	print "<tr><td colspan=\"4\">$tip$tip_site</td></tr>\n";
    	print "<tr><td colspan=\"4\">$copy_kantel</td></tr>\n";
	}
	elsif ($type->{col} == 2)
	{
    	print "<tr><td colspan=\"4\">$advies</td><td colspan=\"4\">$tip$tip_site</td></tr>\n";
    	my $n = 0;
    	for (my $i = 0; $i < $type->{num}; $i++)
   		{
    		print "<tr>";
    		if ($param->{content} eq "kantel")
    		{
	    		for (my $j = 0; $j < $type->{col}; $j++)
	    		{
		    		if ($n < @koop)
		    		{
	   	    			print get_koop_text(@koop[$n], $ref);
		    		}
	    			else
	    			{
	    				print "<td colspan=\"4\">&nbsp;</td>";
	    			}
	    			$n++;
    			}
			}
			elsif ($param->{content} eq "winst")
			{
	    		for (my $j = 0; $j < $type->{col}; $j++)
	    		{
		    		if ($n < @suc)
		    		{
	   	    			print get_success_text(@suc[$n], $ref);
		    		}
	    			else
	    			{
	    				print "<td colspan=\"4\">&nbsp;</td>";
	    			}
	    			$n++;
    			}
			}
			else
			{
				if ($i < @koop)
	    		{
   	    			print get_koop_text(@koop[$i], $ref);
	    		}
	    		else
	    		{
	    			print "<td colspan=\"4\">&nbsp;</td>";
	    		}
	    		if ($i < @suc)
	    		{
   	    			print get_success_text(@suc[$i], $ref);
	    		}
	    		else
	    		{
	    			print "<td colspan=\"4\">&nbsp;</td>";
	    		}
			}
			print "</tr>\n";	    	
    	}
    	print "<tr><td colspan=\"8\">$copy_kantel</td></tr>\n";
	}
	elsif ($type->{col} == 4)
	{
    	print "<tr><td colspan=\"5\">$advies</td><td colspan=\"6\">$tip$tip_site</td><td colspan=\"5\">$copy_kantel</td></tr>\n";
    	my $n = 0;
    	for (my $i = 0; $i < $type->{num}; $i++)
    	{
	    	print "<tr>";
    		if ($param->{content} eq "kantel")
    		{
	    		for (my $j = 0; $j < $type->{col}; $j++)
	    		{
		    		if ($n < @koop) {
	   	    			print get_koop_text(@koop[$n], $ref);
		    		} else {
	    				print "<td colspan=\"4\">&nbsp;</td>";
	    			}
	    			$n++;
    			}
			}
			elsif ($param->{content} eq "winst")
			{
	    		for (my $j = 0; $j < $type->{col}; $j++)
	    		{
		    		if ($n < @suc) {
	   	    			print get_success_text(@suc[$n], $ref);
		    		} else {
	    				print "<td colspan=\"4\">&nbsp;</td>";
	    			}
	    			$n++;
    			}
			}
			else
			{
		    	if ($i < @koop) {
	   	    		print get_koop_text(@koop[$i], $ref);
		    	} else 	{
	    			print "<td colspan=\"4\">&nbsp;</td>";
	    		}
		    	if (($i + $type->{num}) < @koop) {
	   	    		print get_koop_text(@koop[$i + $type->{num}], $ref);
	    		} else {
		    		print "<td colspan=\"4\">&nbsp;</td>";
	    		}
	    		if ($i < @suc) {
	   	    		print get_success_text(@suc[$i], $ref);
	    		} else {
		    		print "<td colspan=\"4\">&nbsp;</td>";
	    		}
	    		if (($i + $type->{num}) < @suc) {
	   	    		print get_success_text(@suc[$i + $type->{num}], $ref);
	    		} else {
		    		print "<td colspan=\"4\">&nbsp;</td>";
	    		}
    		}
			print "</tr>\n";	    	
    	}
	}
	print "</tbody>\n";
    print "</table>\n";
    print "</div>\n";
}

	